from markitdown import MarkItDown
import os
from doc2docx import convert as doc2docx
from shutil import copyfile
import pythoncom


converter = MarkItDown()


def convert(path, base_dir, t):
    base_dir = os.path.abspath(base_dir)
    # 确保 base_dir 是绝对路径
    target_file = os.path.splitext(path.replace(base_dir, base_dir + "-md"))[0] + ".md"

    os.makedirs(os.path.split(target_file)[0], exist_ok=True)  # 确保目标目录存在

    # 使用 MarkItDown 转换文件
    try:
        if path.endswith(".docx") or path.endswith(".xlsx") or path.endswith(".pptx") or path.endswith(".pdf") or path.endswith(".html"):
            markdown_content = converter.convert(path, keep_data_uris=True)

            with open(target_file, "w", encoding="utf-8") as f:
                f.write(markdown_content.text_content)
            t.write(f"转换成功:{target_file}")
            t.update(1)
            return (path, "convert")
        elif path.endswith(".doc"):
            pythoncom.CoInitialize()  # 初始化pythoncom，避免多线程报错
            doc2docx(path, os.path.splitext(path)[0] + ".docx")  # 创建.docx临时文件
            result = convert(os.path.splitext(path)[0] + ".docx", base_dir, t)
            os.remove(os.path.splitext(path)[0] + ".docx")  # 删除临时文件
            return result
        else:
            copyfile(path, target_file)
            t.write(f"格式不支持转换，复制成功:{target_file}")
            t.update(1)
            return (path, "copy")
    except Exception as e:
        t.write(f"转换失败:{path}，错误信息：{e}")
        t.update(1)
        return (path, "error")
